#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include "logger.h"
#include "trunk.h"
#include "trunk_privutils.h"

char *trunk_home = "/trunks";

void mrr_trunk_start() {

}

void mrr_trunk_stop() {

}

struct opened_trunk_info {

	trunk_sn_t sn;

	FILE *file;
};

struct opened_trunk_info *opened;

char code32_table[32]= { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
		'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P',
		'Q', 'R', 'S', 'T', 'U', 'V', 'W', 
};

void fill_and_encode32(unsigned int no, char* encoded) {

	char *buf;

	buf = encoded;
	buf += 7;
	do {
		*buf = code32_table[no & 0x1F];
		buf--;
		no >>= 5;
	} while (no > 0);

	while (buf >= encoded) {
		*buf = '0';
		buf--;
	}
}

char* make_file_path(unsigned int trunkno) {

	int home_strlen;
	int newlen;

	char* result;

	home_strlen = strlen(trunk_home);
	char *p;
	p = trunk_home + home_strlen - 1;
	newlen = home_strlen + 8 + 4 + 1;
	if (*p == '/') {

		result = malloc(sizeof(char*) * newlen);
		memcpy(result, trunk_home, home_strlen);
		p = result + home_strlen;
	} else {

		newlen ++;
		result = malloc(sizeof(char*) * newlen);
		memcpy(result, trunk_home, home_strlen);
		p = result + home_strlen;
		*p = '/';
		p++;
	}

	fill_and_encode32(trunkno, p);
	p+=8;
	*p = '\0';

	strcpy(p, ".mtf");

	return result;
}

int open_trunkfile(unsigned int trunkno, FILE **fh) {

	char *path;
	path = make_file_path(trunkno);

	FILE *f = fopen(path, "r+b");
	if (f != NULL) {
		mrr_debug("open trunk: %s", path);
		free(path);

		*fh = f;
		return 0;
	}

	if (mkdir(trunk_home) == 0) {
		mrr_debug("trunk home created: %s", trunk_home);
	}

	f = fopen(path, "w+b");
	if (f == NULL) {
		mrr_debug("Couldn't open trunk: %s\n", path);
		mrr_sys_errno();
		free(path);
		return 1;
	}
	mrr_debug("new trunk: %s", path);
	free(path);

	// initilze the header of trunk
	char *buf;
	buf = (char*)malloc(TRUNK_HEADER_LENGTH);
	memset(buf, 0, TRUNK_HEADER_LENGTH);
	strcpy(buf, "MTF");
	*(buf + 3) = '\0';
	fwrite(buf, 1, TRUNK_HEADER_LENGTH, f);
	free(buf);

	// initlize the body of trunk
	int buflen;
	buflen = 1 << 20;
	buf = (char*)malloc(buflen);
	memset(buf, 0, buflen);
	int i;
	for (i = 0; i < 16; i ++) {
		if (fwrite(buf, 1, buflen, f) != buflen) {

			mrr_sys_errno();
			free(buf);
			fclose(f);
			return 1;
		}
	}
	free(buf);
	if (fflush(f)!=0) {

		mrr_sys_errno();
		fclose(f);
		return 1;
	}
}
